package com.kun.base.net

import java.util.LinkedHashMap

/**
 * lru缓存
 *  @author : Kun
 *  @date : 2021/4/13
 *  @time : 15:37
 */
class LruCache(private var capacity: Int) {
    /**
     * 缓存的map
     */
    private var cacheMap: LinkedHashMap<Any, Any> = LinkedHashMap(capacity, 0.75f, true)

    /**
     * 获取缓存内容
     */
    fun get(key: Any): Any? {
        return cacheMap.get(key)
    }

    /**
     * 判断是否存在某个缓存
     */
    fun contains(key: Any): Boolean {
        return cacheMap.contains(key)
    }

    /**
     * 设置缓存
     */
    fun put(key: Any, value: Any) {
        if (capacity == 0) {
            return
        }
        if (cacheMap.size == capacity && !cacheMap.containsKey(key)) {
            val entries: Set<Map.Entry<Any, Any>> = cacheMap.entries
            val iterator = entries.iterator()
            cacheMap.remove(iterator.next())
        }
        cacheMap[key] = value
    }

    /**
     * 清空缓存
     */
    fun clear() {
        cacheMap.clear()
    }
}